package com.woniuxy.springmvc.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.omg.CORBA.Request;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.woniuxy.springmvc.entity.User;
import com.woniuxy.springmvc.service.UserService;
@Controller
@RequestMapping("/loginAction")
public class UserAction {

	@Resource 
	private UserService us;
//	@RequestMapping(value="/login" ,method=RequestMethod.POST)
//	public ModelAndView doLogin(HttpServletRequest request,
//			HttpServletResponse response, ModelAndView mv,HttpSession session,
//			User user) throws Exception {
//		String userName =request.getParameter("userName");
//		String passWord =request.getParameter("passWord");
//		//String userName = user.getUserName();
//		//String passWord =user.getPassWoed();
//		//session.setAttribute("user", user);
//		if("a".equals(userName)&&"a".equals(passWord)){
//			mv.addObject("users",this.us.findAll());
//			mv.setViewName("success");
//		}else{
//			mv.setViewName("fail");
//		}
//		return mv;
//	}
	@RequestMapping(value="/login",method=RequestMethod.GET)
	public ModelAndView login(ModelAndView mv)throws Exception{
		mv.setViewName("login");
		return mv;
	}
	@RequestMapping(value="/login" ,method=RequestMethod.POST)
	public String doLogin(User user,HttpSession session){
		String userName =user.getUserName();
		String passWord =user.getPassWord();
		if("a".equals(userName)&&"a".equals(passWord)){
			session.setAttribute("user", user);
			return "redirect:/loginAction/main";
		}else{
		return "fail";
		}	
	}
	@RequestMapping("/main")
	public String main(Model model){
		model.addAttribute("users",this.us.findAll());
		return "success";
	}
	@RequestMapping("/delete/{id}")
	public String delete(@PathVariable("id") int id){
		this.us.deleteUser(id);
		return "redirect:/loginAction/main";
	}
	@RequestMapping("/edit/{id}")
	public String edit(@PathVariable("id")int id,Model model){
		model.addAttribute("edit",this.us.findUserById(id));
		return "edit";
	}
	@RequestMapping("/doEdit")
	public String doEdit(User user){
		this.us.edit(user);
		return "redirect:/loginAction/main";
	}
	
}
